package com.example.kafkademo.commitfailExp;

import org.apache.kafka.clients.consumer.CommitFailedException;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;

import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;

/**
 * @author yanyun zhu
 * @version 1.0
 * @date 2021/12/29 14:15
 * 独立消费者
 *
 * org.apache.kafka.clients.consumer.CommitFailedException: Commit cannot be completed since the group has already rebalanced and
 * assigned the partitions to another member. This means that the time between subsequent calls to poll() was longer than
 * the configured max.poll.interval.ms, which typically implies that the poll loop is spending too much time message processing.
 * You can address this either by increasing max.poll.interval.ms or by reducing the maximum size of batches returned in poll()
 * with max.poll.records.
 */
public class StanaloneConsumer {

    public static void main(String[] args) throws InterruptedException {
        Properties props = new Properties();
        props.put("bootstrap.servers", "10.42.25.12:9092,10.42.25.13:9092,10.42.25.15:9092");
        props.put("group.id", "12334");
        props.put("enable.auto.commit", "false");    //默认true, 自动提交
//        props.put("auto.commit.interval.ms", "2000");     //表明 Kafka 每 5 秒会为你自动提交一次位移(默认)
        props.put(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG, 5000); // 默认5分钟
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
//        consumer.subscribe(Arrays.asList("test-a"));
        //TODO  独立消费者以下不同，指定分区
        TopicPartition topicPartition = new TopicPartition("test-a", 0);   // 独立消费者
        consumer.assign(Arrays.asList(topicPartition));
        while (true) {
            ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(1));
//            process(records); // 处理消息
            if(records.count() > 0){
                System.out.println("88888");
            }
            try {
                consumer.commitSync();    // 支持自动错误重试
            } catch (CommitFailedException e) {
                e.printStackTrace();
//                handle(e); // 处理提交失败异常
            }
        }
    }


}
